/**
 * Created by jt on 2017/5/7.
 */
import "./index.less";
// import "../../../unit/common/js/bootstrap_js/ckeditor.js";
import "../../../unit/common/js/bootstrap_js/select2.min.js";
import "../../../unit/common/js/bootstrap_js/jquery.multi-select.js";
// import "../../../unit/common/js/bootstrap_js/wysihtml5-0.3.0.js";
import "../../../unit/common/js/bootstrap_js/bootstrap-datetimepicker.js";
import "../../../unit/common/js/bootstrap_js/bootstrap-datetimepicker.zh-CN.js";
import "../../../unit/common/js/bootstrap_js/jquery.tagsinput.min.js";
import "../../../unit/common/js/bootstrap_js/bootstrap-colorpicker.js";
import "../../../unit/common/js/bootstrap_js/jquery.inputmask.bundle.min.js";
import "../../../unit/common/js/bootstrap_js/bootstrap-modal.js";
import "../../../unit/common/js/bootstrap_js/bootstrap-modalmanager.js";
import "../../../unit/common/js/bootstrap_js/form-samples.js";
import atchesTpl from "./atches.handlebars";
import designatedSplrsTpl from "./designatedSplrs.handlebars";
import selectSplrsTpl from "./selectSplrs.handlebars";
import suitCompaniesTpl from "./suitCompanies.handlebars";
import {StringUtils} from "../../../unit/common/js/common/StringUtils";

let realName = sessionStorage.getItem("realName");
let mobilephone = sessionStorage.getItem("mobilephone");


jQuery(document).ready(function () {

    let ProjEditObj = {

        allMatTypeList : [],          //所有分类列表
        allMatTypeParentList : [],   //所有一级分类列表
        matkl2html : {},             //所有二级分类列表

        token : sessionStorage.getItem('token'),

        init: function () {
            ProjEditObj.checkLogin();
            jQuery('.logOut').attr('href', '../logins/login.html');
            ProjEditObj.loadWidget();
            // ProjEditObj.setDefaultData();
            ProjEditObj.loadProjInf();
        },

        checkLogin: function () {
            let token = sessionStorage.getItem('token');
            if (StringUtils.isEmptyStr(token)) {
                location.href = HOST_FRT + '/logins/login.html';
            }
        },

        loadProjInf: function () {
            let projId = getArgs().id;
            if (StringUtils.isEmptyStr(projId)) {
                ProjEditObj.renderPage(null);
                return;
            }

            jQuery.ajax({
                url: HOST_ADDR + '/cpmp/bidProjOff/view/' + projId,
                type: 'get',
                dataType: 'json',
                contentType: "application/json",
                headers: {
                    'access_token': ProjEditObj.token,
                    'login_type': 'ums'
                },
                success: function (resp) {
                    if (!resp.success) {
                        alert(resp.msgCod + ' ' + resp.msgInf);
                        return;
                    }

                    ProjEditObj.renderPage(resp.data);
                },
                error: function (err) {
                    console.log(err);
                    alert("系统错误！");
                    return;
                }
            });

        },

        // 控件加载
        loadWidget: function () {
            // 发起公司下拉菜单加载
            let companiesStr = sessionStorage.getItem("manageCompanies");
            let companies = JSON.parse(companiesStr);
            if (companies != null && jQuery.isArray(companies) && companies.length > 0) {
                for (var i = 0; i < companies.length; i++) {
                    if(i==0){
                        jQuery('.bidDptAddr').val(checkNull(companies[i].bidDeptAddr));
                        jQuery('.bidDptNam').val(checkNull(companies[i].bidDept));
                    }
                    jQuery('.orgId').append('<option value="' + companies[i].id + '">' + companies[i].dept_name + '</option>');
                    $(".orgId option[value=" + companies[i].id + "]").data("dataComp",companies[i]);
                }
            }

            // 报价币种加载
            ProjEditObj.loadCurrTyp();

            // 物料品类加载
            ProjEditObj.loadMatInfs();

            // 管理公司加载
            let managedCompanies = JSON.parse(companiesStr);
            let resultHtml = suitCompaniesTpl({suitCompanies: managedCompanies});
            $('.suitCompaniesDiv').html(resultHtml);

        },

        // 加载币种
        loadCurrTyp: function () {
            const parmTyps = 'CURR_TYP';
            const url = HOST_ADDR + '/cpmp/comParm/getByParmTyp/' + parmTyps;
            jQuery.ajax({
                url: url,
                type: 'get',
                dataType: 'json',
                headers: {
                    'access_token': ProjEditObj.token,
                    'login_type': 'ums'
                },
                async: false,
                contentType: 'application/json',
                success: function (resp) {
                    if (!resp.success) {
                        alert(resp.msgCod + " - " + resp.msgInf);
                        console.log(resp.msgCod + " - " + resp.msgInf);
                        return;
                    }

                    if (jQuery.isArray(resp.data) && resp.data.length > 0) {
                        $.each(resp.data,function(idx,val){
                            jQuery('.currTyp').append('<option exRate="' + val.parmVal + '" value="' + val.parmCod + '">' + val.parmMemo + '</option>');
                        });
                    }

                    jQuery('.currTyp').val('RMB');
                    jQuery('.exRate').val("当前汇率：" + $(".currTyp option:selected").attr('exRate'));
                },
                error: function (err) {
                    console.log(err);
                    return;
                }
            });
        },

        // 加载物料品类
        loadMatInfs: function () {
            jQuery.ajax({
                url: HOST_ADDR + '/cpmp/mat/matSapType',
                type: 'get',
                // data: JSON.stringify(data),
                dataType: 'json',
                contentType: "application/json",
                async: false,
                headers: {
                    'access_token': ProjEditObj.token, 'login_type': 'ums'
                },
                success: function (resp) {
                    if (!resp.success) {
                        alert(resp.msgCod + ' ' + resp.msgInf);
                        return;
                    }

                    ProjEditObj.allMatTypeList = resp.data;

                    for (var i=0;i<resp.data.length;i++) {
                        var matkl1 = resp.data[i].matkl1;
                        if(ProjEditObj.allMatTypeParentList.indexOf(matkl1) < 0){
                            ProjEditObj.allMatTypeParentList.push(matkl1);
                            $('.matTyp.matkl1').append('<option value="'+resp.data[i].matkl1+'">'+resp.data[i].matkl1name+'</option>');
                            ProjEditObj.matkl2html[matkl1] = '<option value="'+resp.data[i].matkl1+'">'+resp.data[i].matkl1name+'(全部)</option><option value="'+resp.data[i].matkl2+'">'+resp.data[i].matkl2name+'</option>';
                        }else{
                            ProjEditObj.matkl2html[matkl1] += '<option value="'+resp.data[i].matkl2+'">'+resp.data[i].matkl2name+'</option>';
                        }
                    }

                    $('.matTyp.matkl1').on("change",function(){
                        $('.matTyp.matkl2').html("");
                        var tmpmatkl1 = $('.matTyp.matkl1').val();
                        if(tmpmatkl1){
                            $('.matTyp.matkl2').html(ProjEditObj.matkl2html[tmpmatkl1]);
                        }
                    });

                },
                error: function (err) {
                    console.log(err);
                    return;
                }
            });
        },

        renderPage: function (data) {
            if (data == null) {
                data = {
                    bidProjOff: {
                        currTyp : "RMB",
                        dpstFlg : '0',
                        bidOpenTim : '',
                        bidEndTim : '',
                        projMemo : '',
                        ctct : realName,
                        ctctTel : mobilephone,
                    },

                    'splrs': [],
                    'atches': []
                };
            }


            // 日期相关
            let bidOpenTim = '';
            let bidEndTim = '';
            let projMemo = '';
            if (!StringUtils.isEmptyStr(data.bidProjOff.bidOpenTim)) {
                bidOpenTim = (new Date(data.bidProjOff.bidOpenTim)).Format("yyyy-MM-dd hh:mm");
            }
            if (!StringUtils.isEmptyStr(data.bidProjOff.bidEndTim)) {
                bidEndTim = (new Date(data.bidProjOff.bidEndTim)).Format("yyyy-MM-dd hh:mm");
            }
            if (!StringUtils.isEmptyStr(data.bidProjOff.projMemo)) {
                projMemo = data.bidProjOff.projMemo;
            }

            if (!StringUtils.isEmptyStr(data.bidProjOff.orgId)) {
                jQuery('.orgId').val(data.bidProjOff.orgId);
            }

            for (var i = 0; i < ProjEditObj.allMatTypeList.length; i++) {
                if (data.bidProjOff.matTyp === ProjEditObj.allMatTypeList[i].matkl1 || data.bidProjOff.matTyp === ProjEditObj.allMatTypeList[i].matkl2) {
                    jQuery('.matTyp.matkl1').val(ProjEditObj.allMatTypeList[i].matkl1);
                    jQuery('.matTyp.matkl2').html(ProjEditObj.matkl2html[ProjEditObj.allMatTypeList[i].matkl1]);
                    jQuery('.matTyp.matkl2').val(data.bidProjOff.matTyp);
                }
            }


            jQuery('.projNam').val(data.bidProjOff.projNam);
            if(data.bidProjOff.bidDpt != '' && data.bidProjOff.bidDpt != null){
                jQuery('.bidDptNam').val(data.bidProjOff.bidDpt);
                jQuery('.bidDptAddr').val(data.bidProjOff.bidDptAddr);
            }
            jQuery('.ctct').val(data.bidProjOff.ctct);
            jQuery('.ctctTel').val(data.bidProjOff.ctctTel);
            jQuery('.bidOpenTimStr').val(bidOpenTim);
            jQuery('.bidEndTimStr').val(bidEndTim);
            jQuery('.projMemo').val(projMemo);
            jQuery('.bidRngTyp').val(data.bidProjOff.bidRngTyp);
            jQuery('.simditor-body').html(data.bidProjOff.bidBok);
            jQuery('.matReqDept').val(data.bidProjOff.matReqDept);
            jQuery('.bidTeamMmb').val(data.bidProjOff.bidTeamMmb);

            // 投标保证金相关
            let dpstFlg = data.bidProjOff.dpstFlg;
            if (StringUtils.isEmptyStr(dpstFlg) || dpstFlg == '0') {
                jQuery('.dpstFlg').val('0');
                jQuery('.bidDpst').attr('disabled', 'disabled').val(0);
            } else {
                jQuery('.dpstFlg').val(data.bidProjOff.dpstFlg);
                jQuery('.bidDpst').removeAttr('disabled');
                jQuery('.bidDpst').val(data.bidProjOff.bidDpst);
            }

            // 发布招标价格公开标识
            jQuery('.pubPriFlg').val(data.bidProjOff.pubPriFlg);

            // 附件相关
            ProjEditObj.displayAtches(data.atches);

            // 适用公司相关
            var orgIds = data.bidProjOff.sutOrgIds;
            if (orgIds != null && typeof orgIds != 'undefined' && orgIds != '') {
                var orgidlist = orgIds.split(",");

                if (jQuery.isArray(orgidlist)) {
                    if (orgidlist.length > 0) {   // 已选择的适用公司IDs.

                        let cboxs = jQuery('.selectedCompanies');
                        if (cboxs.length > 0) {
                            for (let i = 0; i < cboxs.length; i++) {
                                for (let j = 0; j < orgidlist.length; j++) {
                                    if (cboxs.eq(i).val() === orgidlist[j]) {
                                        cboxs.eq(i).attr('checked', 'checked');
                                    }
                                }

                            }
                        }
                    }
                }
            }


            // 招标范围相关
            var bidRngTyp = data.bidProjOff.bidRngTyp;
            if (typeof(bidRngTyp) == 'undefined' || bidRngTyp == null || bidRngTyp == '') {
                bidRngTyp = '0';
            }
            jQuery('.bidRngTyp').val(bidRngTyp);
            ProjEditObj.changeBidRngTyp();

            // 若为定向招标
            if (bidRngTyp === '1') {
                if (data.splrs != null && data.splrs != '') {
                    ProjEditObj.displayDesignatedSplrs(data.splrs);
                }
            }
        },

        displayDesignatedSplrs: function (designatedSplrs) {
            let resultHtml = designatedSplrsTpl({designatedSplrs: designatedSplrs});
            $('.designatedSplrsDiv').html(resultHtml);

            //删除整行
            jQuery('.deleteDesignatedSplr').click(function () {
                var _this = jQuery(this);
                _this.parent('td').parent('tr').remove();
            });
        },

        getAtches: function () {
            var atches = [];
            var atchObjs = jQuery('#atches tr');

            for (var j = 0; j < atchObjs.length; j++) {
                atches.push({
                    "atchUrl": atchObjs.eq(j).attr('atchUrl')
                    , "atchNam": atchObjs.eq(j).attr('atchNam')
                });
            }

            return atches;
        },

        displayAtches: function (atches) {
            $.each(atches,function(idx,val){
                val.atchUrlFmt = HOST_FILE + val.atchUrl;
            });

            let resultHtml = atchesTpl({atches: atches});
            $('.atchFilesDiv').html(resultHtml);

            //删除整行
            jQuery('.deleteAtch').click(function () {
                var _this = jQuery(this);
                _this.parent('td').parent('tr').remove();
            });
        },

        changeBidRngTyp: function () {
            var bidRngTyp = jQuery('.bidRngTyp').val();
            if (bidRngTyp === '0') {
                jQuery('.designatedSplrsBtnFormActionArea').hide();
                jQuery('.designatedSplrsDiv').hide();
                ProjEditObj.displayDesignatedSplrs([]);
            } else if (bidRngTyp === '1') {
                if (!jQuery('.matTyp.matkl2').val()) {
                    alert("请先选择物料分类");
                    jQuery('.bidRngTyp').val('0');
                    return;
                }
                jQuery('.designatedSplrsBtnFormActionArea').show();
                jQuery('.designatedSplrsDiv').show();
                ProjEditObj.displayDesignatedSplrs([]);
            }
        }

    };


    App.init();
    ProjEditObj.init();

    // 切换币种
    jQuery('.currTyp').change(function () {
        // console.log(exRate);
        jQuery('.exRate').val("当前汇率：" + $(".currTyp option:selected").attr('exRate'));
    });


    // 切换投标保证金缴纳标识
    jQuery('.dpstFlg').change(function () {
        if (jQuery(this).val() == 0) {
            jQuery('.needPri').hide();
            jQuery('.bidDpst').attr('disabled', 'disabled');
            jQuery('.bidDpst').val(0);
        } else if (jQuery(this).val() == 1) {
            jQuery('.needPri').show();
            jQuery('.bidDpst').removeAttr('disabled');
        }
    });

    // 切换发起公司
    $(".orgId").change(function () {
        var orgid = $(this).val();
        // var tmpCompany = $(".controls.OrgIds input[value=" + orgid + "]").data("dataComp");
        var tmpCompany = $(".orgId option[value=" + orgid + "]").data("dataComp");
        jQuery('.bidDptAddr').val(checkNull(tmpCompany.bidDeptAddr));
        jQuery('.bidDptNam').val(checkNull(tmpCompany.bidDept));
    });


    //新增附件
    jQuery('.addFile').click(function () {
        jQuery('#atchFile').click();
        $("#atchFile").unbind().change(function(){
            let formData = new FormData();
            let atchNam=$("#atchFile")[0].files[0].name;
            let atchUrl;
            formData.append('file', $("#atchFile")[0].files[0]);
            $.ajax({
                url: HOST_ADDR+'/cpmp/file/upload/atch',
                type: 'post',
                cache: false,
                data: formData,
                processData: false,
                contentType: false,
                success: function(resp){
                    if(resp.success){
                        console.log(resp);
                        atchUrl = resp.data;
                        let atches = ProjEditObj.getAtches();
                        atches.push({
                            "atchUrl" : atchUrl,
                            "atchNam" : atchNam
                        });

                        ProjEditObj.displayAtches(atches);

                    }else{
                        alert(resp.msgCod + " | " + resp.msgInf);
                    }
                },
                error:function(err){
                    alert('上传文件失败！');
                }
            });
        });
    });


    //定向招标获取供应商
    jQuery('.bidRngTyp').change(function () {
        ProjEditObj.changeBidRngTyp();
    });


    var flg = true;
    // 保存   提交审核
    jQuery(".form-actions a[type='submit']").on("click", function () {
        let subFlg = 0; // 保存
        if (jQuery(this).hasClass("subCheck")) {  // 提交审核
            subFlg = 1; // 提交审核
            if (!flg) {
                alert("请勿重复提交");
                return false;
            }
            flg = false;
            setTimeout(function () {
                flg = true;
            }, 3000);
        } else if (jQuery(this).hasClass("subKeep")) {
            subFlg = 0; // 保存
        } else {
            return false;
        }
        let projId = getArgs().id;
        let orgId = jQuery('.orgId').val();
        let projName = jQuery('.projNam').val();
        let bidDptNam = jQuery('.bidDptNam').val();
        let bidDptAddr = jQuery('.bidDptAddr').val();
        let matTyp = jQuery('.matTyp.matkl2').val();
        let bidDpst = jQuery('.bidDpst').val();
        let ctct = jQuery('.ctct').val();
        let ctctTel = jQuery('.ctctTel').val();
        let projMemo = jQuery('.projMemo').val();
        let currTyp = jQuery('.currTyp').val();
        let dpstFlg = jQuery('.dpstFlg').val();
        let pubPriFlg = jQuery('.pubPriFlg').val();
        let bidBok = editor.getValue();
        let atchDtos = [];
        // let atchDiv = jQuery('.atchDiv');
        let bidRngTyp = jQuery('.bidRngTyp').val();
        let splrIds = '';
        if (bidRngTyp === '1') {
            let splrIdList = [];

            let designatedSplrObjs = jQuery('#designatedSplrs tr');
            for (let j = 0; j < designatedSplrObjs.length; j++) {
                splrIdList.push(designatedSplrObjs.eq(j).find('td').eq(0).text());
            }

            splrIds = splrIdList.join(',');
            if(splrIds == null || splrIds == '') {
                alert("定向招标时，指定招标供应商不得为空！");
                return;
            }

        }


        let sutOrgIds = '';

        let orgIdList = [];

        jQuery(".selectedCompanies:checked").each(function() {
            orgIdList.push(jQuery(this).val());
        });
        sutOrgIds = orgIdList.join(',');
        if(sutOrgIds == null || sutOrgIds == '') {
            alert("请选择适用公司！");
            return;
        }

        // 附件
        let atchesObj = jQuery('#atches tr');
        for (let j = 0; j < atchesObj.length; j++) {
            atchDtos.push({
                "atchUrl": atchesObj.eq(j).attr('atchUrl'),
                "atchNam": atchesObj.eq(j).attr('atchNam')
            });
        }
        if (projName == '') {
            alert('请填写项目名称！');
            return;
        }
        if (bidDptNam == '') {
            alert('请填写单位名称！');
            return;
        }
        if (bidDptAddr == '') {
            alert('请填写单位地址！');
            return;
        }
        if (matTyp == '') {
            alert('请填写物料类型！');
            return;
        }
        if (dpstFlg == '1') {
            if (bidDpst == '') {
                alert('请填写投标保证金！');
                return;
            } else if (!/^\d+(\.\d{0,2})?$/.test(bidDpst)) {
                alert('保证金必须为数字，最多保留两位小数！');
                return;
            }
        }
        if (currTyp == '') {
            alert('请选择币种！');
            return;
        }
        if (dpstFlg == '') {
            alert('请选择是否需要投标保证金！');
            return;
        }
        if (pubPriFlg == '') {
            alert('请选择是否需要公开招标价格！');
            return;
        }
        if (ctct == '') {
            alert('请填写联系人！');
            return;
        }
        if (ctctTel == '') {
            alert('请填写联系电话！');
            return;
        } else {
            var tel1 = /^1(3|4|5|7|8)\d{9}$/;
            var tel2 = /^\d{3,4}-?\d{7,9}$/;
            if (!tel1.test(ctctTel) && !tel2.test(ctctTel)) {
                alert('请填写正确格式的联系电话！');
                return;
            }
        }
        if (bidRngTyp == '') {
            alert('请填写招标范围类型！');
            return;
        } else if (bidRngTyp == '1') {
            if (splrIds.length == 0) {
                alert('如果定向招标，请选择定向供应商！');
            }
        }
        if (bidBok == '') {
            alert('请填写招标书详情！');
            return;
        }
        let data = {
            "subFlg": subFlg,
            "orgId": orgId,
            "sutOrgIds": sutOrgIds,
            "projId": projId,
            "projNam": projName,
            "bidDpt": bidDptNam,
            "bidDptAddr": bidDptAddr,
            "matTyp": matTyp,
            "bidDpst": bidDpst,
            "ctct": ctct,
            "ctctTel": ctctTel,
            "bidRngTyp": bidRngTyp,
            "projMemo": projMemo,
            "bidBok": bidBok,
            "bidOpenTimStr": jQuery('.bidOpenTimStr').val() + ':00',
            "bidEndTimStr": jQuery('.bidEndTimStr').val() + ':00',
            "aptSplrIds": splrIds,
            "currTyp": currTyp,
            "dpstFlg": dpstFlg,
            "pubPriFlg": pubPriFlg,
            "atchDtos": atchDtos,
            "matReqDept" : jQuery('.matReqDept').val(),
            "bidTeamMmb" : jQuery('.bidTeamMmb').val()
        };
        console.log(data);

        jQuery.ajax({
            url: HOST_ADDR + '/cpmp/bidProjOff/saveOrSub',
            type: 'post',
            data: JSON.stringify(data),
            dataType: 'json',
            contentType: "application/json",
            headers: {
                'access_token': ProjEditObj.token, 'login_type': 'ums'
            },
            success: function (resp) {
                if (!resp.success) {
                    alert(resp.msgCod + ' ' + resp.msgInf);
                    return;
                }
                console.log(resp);
                // //页面跳转到index
                subFlg == 1 ? alert("提交成功！") : alert("保存成功！");
                location.href = 'proj_list.html';

            },
            error: function (err) {
                console.log(err);
            }
        });
    });

    function checkNull(val) {
        if (val != null && val != '' && val != 'undefined') {
            //
        } else {
            val = '';
        }
        return val;
    }

    jQuery('.datetimepicker').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        minView: 0, //0表示分钟（默认），1表示小时，而2表示天
        forceParse: 0,
        showMeridian: 1,
        format: 'yyyy-mm-dd hh:ii'///
    });


    jQuery('.designatedSplrsBtn').click(function () {
        jQuery.ajax({
            url: HOST_ADDR+'/cpmp/mat/splrByMatType',
            type: 'get',
            dataType: 'json',
            contentType:"application/json",
            headers: {
                splrSts:"03,05",
                matType: jQuery('.matTyp.matkl2').val(),
                'access_token': ProjEditObj.token,'login_type':'ums'
            },
            success: function(resp){
                if (!resp.success) {
                    alert(resp.msgCod+' '+resp.msgInf);
                    return;
                }
                console.log(resp);

                // TODO

                $('.designateSplrsTable').html('');
                let resultHtml = selectSplrsTpl({selectSplrs: resp.data});
                $('.designateSplrsTable').html(resultHtml);

                $('#designateSplrsModal').modal('show');
            },
            error:function(err){

                console.log(err);
            }
        });
    });

    jQuery('.designateSplrs_ok').click(function () {

        var designatedSplrs =[];
        var splrs = jQuery('#selectSplrs tr');

        for (var j = 0; j < splrs.length; j++) {
            // 判断是否选中
            var checked = splrs.eq(j).find('td').eq(0).find('input').is(':checked');
            if (checked) {
                designatedSplrs.push({
                    "splrId" : splrs.eq(j).find('td').eq(1).text()
                    , "splrNam" : splrs.eq(j).find('td').eq(4).text()
                });
            }
        }

        ProjEditObj.displayDesignatedSplrs(designatedSplrs);

        $('#designateSplrsModal').modal('hide');
    });


    jQuery('.viewExRate').click(function () {
        alert('敬請期待!');
        // window.open(HOST_ADDR + "/show", "_blank");
    });

});